/*
PHPwork上传文件管理器
*/


$(function(){

    // 选中的删除
    $('body').on('click','.phpwork-uploader_list .phpwork-item > img',function(){
        $(this).parent().remove();
    });

});

// 入口 文件库管理 multiple一个文件 false   多个文件true
function phpwork_file_manage( input_name='file' , config={"accept":"images","multiple":false} ,callback=null ){
    var loadIndex = layer.load();

    $.ajax({
        url: '?s=api/upload/file_list&app_name=' + _MODULE_NAME_ ,//"<?php echo url('api/upload/file_list',['app_name'=>_MODULE_NAME_]);?>",
        type: 'get',
        dataType:'json',
        success: function (res) {
            layer.close(loadIndex);
            //console.log(res);
            if (res.code === 200) {

                var tmp_html='';
                tmp_html += '<div class="phpwork-file_list_head">';
                tmp_html += '<span class="phpwork-btn_delete"><i class="layui-icon layui-icon-delete"></i> 删除</span>';
                tmp_html += '<label class="phpwork-btn_upload" id="upload_'+input_name+'"><i class="layui-icon layui-icon-addition"></i> 上传</label>';
                tmp_html += '</div>';

                tmp_html += '<div class="phpwork-file_list_body">';
                for(var i =0 ; i< res.data.length ; i++ ){
                    tmp_html += '<div class="phpwork-item" data-file="'+ res.data[i] +'" >';
                    var f_ext = res.data[i].split('.').pop().toLowerCase() ;
                    if( f_ext === 'jpg' || f_ext === 'jpeg' || f_ext === 'png' || f_ext === 'gif' || f_ext === 'bmp' ){
                        tmp_html += '<img src="' + _APP_URL_  + '/data/uploadfile/' + _MODULE_NAME_  + '/'+ res.data[i] +'" title="' + res.data[i] + '" loading="lazy">';
                    }else{
                        tmp_html += '<img src="' + _APP_URL_  + '/library/deep/upload/ico/' +  f_ext +'.png" title="' + res.data[i] + '" >';
                    }  
                    tmp_html += '<div  class="phpwork-file_name">' + res.data[i] + '</div>';
                    tmp_html += '<div class="phpwork-mask"><img src="' + _APP_URL_  + '/library/deep/upload/mask.png" ></div>';
                    tmp_html += '</div>';
                }
                tmp_html += '</div>';
                

                layer.open({
                    type: 1    //页面层
                    , title:'文件库'
                    , skin: 'phpwork-file_library'
                    , area: '850px'
                    , offset: 'auto'
                    , anim: 1
                    , closeBtn: 1
                    , shade: 0.3
                    , content:  tmp_html //这里content是一个DOM
                    , btn: ['确定', '取消']
                    , success: function () { // 初始化文件库弹窗
                        
                        //上传
                        layui.upload.render({
                            elem: '#upload_' + input_name
                            ,url: '?s=api/upload/file_upload&app_name=' + _MODULE_NAME_   //改成您自己的上传接口
                            ,field :'file'
                            ,accept: config.accept //允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
                            ,before: function(o){ //o参数包含的信息，跟 choose回调完全一致，可参见上文。
                                layer.load(); //上传loading
                            }
                            ,done: function(data){//上传完毕回调
                                layer.closeAll('loading'); //关闭loading
                                layer.msg('上传成功!', { anim: 1 });
                    
                                var tmp_html='';						
                                tmp_html += '<div class="phpwork-item" data-file="' + data.data.file_name +'" >';
                                var f_ext = data.data.file_name.split('.').pop().toLowerCase() ;
                                if( f_ext === 'jpg' || f_ext === 'jpeg' || f_ext === 'png' || f_ext === 'gif' || f_ext === 'bmp' ){
                                    tmp_html += '<img src="' + _APP_URL_  + '/data/uploadfile/' + _MODULE_NAME_  + '/'+ data.data.file_name +'" title="' + data.data.file_name + '" loading="lazy">';
                                }else{
                                    tmp_html += '<img src="' + _APP_URL_  + '/library/deep/upload/ico/' +  f_ext +'.png" title="' + data.data.file_name + '" >';
                                }  
                                tmp_html += '<div  class="phpwork-file_name">' + data.data.file_name + '</div>';
                                tmp_html += '<div class="phpwork-mask"><img src="' + _APP_URL_  + '/library/deep/upload/mask.png" ></div>';
                                tmp_html += '</div>';
                                $('.phpwork-file_list_body').prepend(tmp_html);
                            }
                            ,error: function(res){//请求异常回调
                                layer.closeAll('loading'); //关闭loading
                                layer.msg(res.message, { anim: 6 });                                                    
                            }
                        });


                        //事件
                        $('.phpwork-file_list_body').on('click',' .phpwork-item',function(){
                            if($(this).find('.phpwork-mask').css('display')=='none'){
                                $(this).find('.phpwork-mask').css('display','block');
                            }else{
                                $(this).find('.phpwork-mask').css('display','none');
                            }
                            $(this).toggleClass('phpwork-active');
                        });
                        
                        $('.phpwork-btn_delete').on('click',function(){
                            var fileIds = $('.phpwork-file_list_body > .phpwork-active');
                            //console.log(fileIds);
                            if (fileIds.length === 0) {
                                layer.msg('您还没有选择任何文件!', { anim: 6 });
                                return;
                            }
                            
                            var _src=[]; 
                            fileIds.each(function(i){
                               _src[i] =  $(this).attr('data-file') ;
                               //console.log($(this).attr('data-file'));
                            });

                            layer.confirm('确定删除选中的文件吗？', { title: '友情提示' }, function (index) {
                                var load = layer.load();
                                $.ajax({
                                    contentType: 'application/json;charset=UTF-8',
                                    url: '?s=api/upload/file_delete&app_name=' + _MODULE_NAME_ , //"<?php echo url('api/upload/file_delete',['app_name'=>_MODULE_NAME_]);?>",
                                    data: 'file=' + _src.join(),
                                    type: 'get',
                                    dataType:'json',
                                    success: function (res) {
                                        layer.close(load);
                                        layer.close(index);
                                        if (res.code === 200) {
                                            $('.phpwork-file_list_body > .phpwork-active').remove();
                                        }else{
                                            layer.msg(res.message, { anim: 6 });    
                                        }

                                    },
                                    error: function(res) { 
                                        layer.close(load);
                                        layer.close(index);
                                        layer.msg( res.message , { anim: 6 });
                                    }

                                })
                            });
                        });

                        
                    }
                    , yes: function (index) {   // 确认回调
                            var fileIds = $('.phpwork-file_list_body > .phpwork-active');
                            //console.log(fileIds);
                            if (fileIds.length === 0) {
                                layer.msg('您还没有选择任何文件!', { anim: 6 });
                                return;
                            }
                            
                            if( $('.phpwork-tmp_' + input_name).length === 0 ){
                                $('#phpwork-tmp_btn_'+ input_name ).after('<div class="phpwork-uploader_list phpwork-tmp_' + input_name + '"></div>'); // class名 实现页内多次调用
                            }
                            $('.phpwork-tmp_' + input_name ).sortable();
                            //console.log(input_name);
                            
                            var _src=[]; 
                            fileIds.each(function(i){ // 选择的文件 到页面
                               _src[i] =  $(this).attr('data-file') ;
                               _src[i] = 'data/uploadfile/'+_MODULE_NAME_+ '/' + _src[i];
                               //console.log($(this).attr('data-file'));
                                tmp_html = '<div class="phpwork-item" >';
                                tmp_html += '<a href="' + _APP_URL_  + '/' + _src[i] +'" target="_blank">';
                                
                                var f_ext = _src[i].split('.').pop().toLowerCase() ;
                                if( f_ext === 'jpg' || f_ext === 'jpeg' || f_ext === 'png' || f_ext === 'gif' || f_ext === 'bmp' ){
                                    tmp_html += '<img src="' + _APP_URL_ + '/' + _src[i] +'" title="点击查看大图\n' + _src[i] + '" loading="lazy" >';
                                }else{
                                    tmp_html += '<img src="' + _APP_URL_  + '/library/deep/upload/ico/' +  f_ext +'.png" title="点击查看文件\n' + _src[i] + '" >';
                                }  
                                tmp_html += '</a>';
                                tmp_html += '<img src="' + _APP_URL_  + '/library/deep/upload/close.png" title="删除" >';
                                if( config.multiple === true ){
                                    tmp_html += '<input type="hidden" name="'+ input_name +'[]" value="' + _src[i] +'" >';
                                }else{
                                    tmp_html += '<input type="hidden" name="'+ input_name +'" value="' + _src[i] +'" >';
                                }

                                tmp_html += '</div>';
                                if( config.multiple === true ){
                                    //$('.phpwork-tmp_'+ input_name).append(tmp_html);
                                    $('#phpwork-tmp_btn_'+ input_name).before(tmp_html);
                                }else{
                                    //$('.phpwork-tmp_'+ input_name).html(tmp_html);
                                    $('.phpwork-tmp_'+ input_name +' .phpwork-item').remove();
                                    $('#phpwork-tmp_btn_'+ input_name).before(tmp_html);

                                }
                                
                            });
                            
                            layer.close(index);
							
							// 回调函数
							typeof(callback)==='function' && callback(_src);
                        }

                });

            } else {
                layer.msg(res.message, { anim: 6 });
                return false;
            }
        }
    });



}

